package com.michaelwolf.mytool.ruwlsr;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class Job {
	
	private JobInfo jobInfo;
	
	private List<String> resultStringsList =  new ArrayList<String>();

	public Job(JobInfo ji) {
		this.jobInfo = ji;
	}

	public void doJob() throws IOException {
		String usingStrContent = jobInfo.getUsingStrContent().toString();
		
		List<String> stringsList = jobInfo.getStringList();
		for(String str : stringsList){
			
			String id = getStrID(str);
			
			if(alwaysKeepContent(str) || usingStrContent.contains(id)){
				resultStringsList.add(str);
			}
		}
		
		writeNewResultToFile();
		
	}

	private boolean alwaysKeepContent(String str) {
		if(str.startsWith("#") || str.startsWith("module"))
			return true;
		else
			return false;
	}

	private String getStrID(String str) {
		if(str.startsWith("#")) 
			return str;
		
		
		String[] strParts = str.split("=");
		
		String IDPart = strParts[0];
		
		if(IDPart.startsWith("plain"))
			return IDPart;
		else{
			String[] IDPartDetails = IDPart.split("\\.");
			return IDPartDetails[1];
		}
	}

	private void writeNewResultToFile() throws IOException {
		File stringFile = jobInfo.getStringFile();
		String path = stringFile.getPath();
		stringFile = new File(path+"2");
		
		
		OutputStream os = new FileOutputStream(stringFile);
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
		
		try{
			for(String str : resultStringsList){
				writer.write(str);
				writer.newLine();
			}
		}finally{
			writer.close();
		}
		
		
		
	}

}
